05. Enums

Enums

ND079 C1 L4 A05 Enums

What is an Enum?

In many cases when developing software we need to provide a predefined value for a single variable type. Enumerations (or Enums for short) are a special data type of constants that allow a variable to be set from an enumerated list.

An Enum is a Class

In Java, the declaration of an Enum defines a class. This class can exist within another class or as a standalone class.

In some cases, we might only need to use the Enum type within a single class (as would probably be the case with the stoplight example). In that case it would be acceptable to define it within another class rather than as a standalone. However, if other classes are expected to use the enum type, it should be defined as a separate, standalone class.

Syntax Example

Below is an example of how to create a stoplight enum like we showed in the video. Notice that we have created three constants, RED, YELLOW, and GREEN. In Java, it is standard to put the values of enums in uppercase to indicate that they are constants.

Creating an Enum

enum Stoplight {
  RED,
  YELLOW,
  GREEN
}

Assigning a Variable

Next, we will assign a variable, myStopLight, with the RED enum.

Stoplight myStoplight = Stoplight.RED;

Defining an Enum Inside a Class

We can also create an enum from inside a class:

public class Main {
  enum StopLight {
    RED,
    YELLOW,
    GREEN
  }

  public static void main(String[] args) {
    StopLight myStoplight = Stoplight.RED; 
    System.out.println(myStoplight);
  }
}

Select the correct statement about enumerations (enums).

SOLUTION: Enums are a special data type of constants that allow a variable to be set from an enumerated list.